import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { CloudDataManager } from '../../utils/cloud'
import './index.scss'

interface Notification {
  id: string;
  userId: string;
  title: string;
  content: string;
  type: string;
  isRead: boolean;
  createdAt: Date;
}

interface NotificationCenterProps {
  onClose: () => void;
}

const NotificationCenter: React.FC<NotificationCenterProps> = ({ onClose }) => {
  const { state } = useAppContext()
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [loading, setLoading] = useState(true)
  const [unreadCount, setUnreadCount] = useState(0)
  
  // 初始化时加载通知
  useEffect(() => {
    if (state.currentUser?.id) {
      fetchNotifications()
    }
  }, [state.currentUser])
  
  // 获取用户通知
  const fetchNotifications = async () => {
    if (!state.currentUser?.id) return
    
    setLoading(true)
    try {
      // 获取通知数据
      const data = await CloudDataManager.getAllData('notifications', { 
        userId: state.currentUser.id 
      }) as Notification[]
      
      // 格式化日期并按时间倒序排序
      const formattedData = data.map(item => ({
        ...item,
        createdAt: new Date(item.createdAt)
      })).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
      
      setNotifications(formattedData)
      
      // 计算未读通知数量
      const unread = formattedData.filter(item => !item.isRead).length
      setUnreadCount(unread)
    } catch (error) {
      console.error('获取通知失败:', error)
    } finally {
      setLoading(false)
    }
  }
  
  // 标记通知为已读
  const markAsRead = async (notificationId: string) => {
    try {
      await CloudDataManager.updateData('notifications', notificationId, {
        isRead: true,
        updatedAt: new Date()
      })
      
      // 更新本地通知列表
      setNotifications(prev => 
        prev.map(item => 
          item.id === notificationId 
            ? { ...item, isRead: true } 
            : item
        )
      )
      
      // 更新未读数量
      setUnreadCount(prev => Math.max(0, prev - 1))
    } catch (error) {
      console.error('标记通知已读失败:', error)
    }
  }
  
  // 标记所有通知为已读
  const markAllAsRead = async () => {
    if (notifications.length === 0 || unreadCount === 0) return
    
    try {
      // 获取所有未读通知ID
      const unreadIds = notifications
        .filter(item => !item.isRead)
        .map(item => item.id)
      
      // 批量更新
      for (const id of unreadIds) {
        await CloudDataManager.updateData('notifications', id, {
          isRead: true,
          updatedAt: new Date()
        })
      }
      
      // 更新本地通知列表
      setNotifications(prev => 
        prev.map(item => ({ ...item, isRead: true }))
      )
      
      // 更新未读数量
      setUnreadCount(0)
      
      Taro.showToast({
        title: '已全部标记为已读',
        icon: 'success'
      })
    } catch (error) {
      console.error('标记所有通知已读失败:', error)
      Taro.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  }
  
  // 删除通知
  const deleteNotification = async (notificationId: string) => {
    try {
      await CloudDataManager.deleteData('notifications', notificationId)
      
      // 更新本地通知列表
      const updatedNotifications = notifications.filter(item => item.id !== notificationId)
      setNotifications(updatedNotifications)
      
      // 如果删除的是未读通知，更新未读数量
      const deletedItem = notifications.find(item => item.id === notificationId)
      if (deletedItem && !deletedItem.isRead) {
        setUnreadCount(prev => Math.max(0, prev - 1))
      }
    } catch (error) {
      console.error('删除通知失败:', error)
      Taro.showToast({
        title: '删除失败',
        icon: 'none'
      })
    }
  }
  
  // 清空所有通知
  const clearAllNotifications = async () => {
    if (notifications.length === 0) return
    
    Taro.showModal({
      title: '确认清空',
      content: '确定要清空所有通知吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 批量删除
            for (const notification of notifications) {
              await CloudDataManager.deleteData('notifications', notification.id)
            }
            
            // 清空本地通知列表
            setNotifications([])
            setUnreadCount(0)
            
            Taro.showToast({
              title: '已清空所有通知',
              icon: 'success'
            })
          } catch (error) {
            console.error('清空通知失败:', error)
            Taro.showToast({
              title: '操作失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }
  
  // 获取通知类型图标
  const getNotificationIcon = (type: string): string => {
    switch (type) {
      case 'order_status':
        return '📦'
      case 'points_expired':
        return '⏰'
      case 'level_upgrade':
        return '🏆'
      case 'birthday':
        return '🎂'
      case 'system':
        return '🔔'
      default:
        return '📝'
    }
  }
  
  // 格式化日期
  const formatDate = (date: Date): string => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    // 一小时内
    if (diff < 60 * 60 * 1000) {
      const minutes = Math.floor(diff / (60 * 1000))
      return `${minutes}分钟前`
    }
    
    // 一天内
    if (diff < 24 * 60 * 60 * 1000) {
      const hours = Math.floor(diff / (60 * 60 * 1000))
      return `${hours}小时前`
    }
    
    // 一周内
    if (diff < 7 * 24 * 60 * 60 * 1000) {
      const days = Math.floor(diff / (24 * 60 * 60 * 1000))
      return `${days}天前`
    }
    
    // 更早
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
  
  return (
    <View className='notification-center'>
      <View className='notification-header'>
        <Text className='header-title'>通知中心</Text>
        <Text className='close-button' onClick={onClose}>×</Text>
      </View>
      
      <View className='notification-actions'>
        <Text className='unread-count'>{unreadCount}条未读</Text>
        <View className='action-buttons'>
          <Text 
            className='action-button'
            onClick={markAllAsRead}
          >
            全部已读
          </Text>
          <Text 
            className='action-button'
            onClick={clearAllNotifications}
          >
            清空通知
          </Text>
        </View>
      </View>
      
      {loading ? (
        <View className='loading-state'>
          <Text>加载中...</Text>
        </View>
      ) : notifications.length === 0 ? (
        <View className='empty-state'>
          <Text>暂无通知</Text>
        </View>
      ) : (
        <ScrollView 
          scrollY 
          className='notification-list'
        >
          {notifications.map(notification => (
            <View 
              key={notification.id} 
              className={`notification-item ${notification.isRead ? 'read' : 'unread'}`}
              onClick={() => !notification.isRead && markAsRead(notification.id)}
            >
              <View className='notification-icon'>
                {getNotificationIcon(notification.type)}
              </View>
              <View className='notification-content'>
                <View className='notification-header'>
                  <Text className='notification-title'>{notification.title}</Text>
                  <Text className='notification-time'>{formatDate(notification.createdAt)}</Text>
                </View>
                <Text className='notification-text'>{notification.content}</Text>
              </View>
              <Text 
                className='delete-button'
                onClick={(e) => {
                  e.stopPropagation()
                  deleteNotification(notification.id)
                }}
              >
                删除
              </Text>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  )
}

export default NotificationCenter 